package cli

import (
	"fmt"

	"gitee.com/libgitee/go-course-go7/store/aliyun"
	"gitee.com/libgitee/go-course-go7/store/tx"
	"gitee.com/libgitee/go-course-go7/store/aws"
	"gitee.com/libgitee/go-course-go7/store"
	"github.com/spf13/cobra"
)

var (
	// 4. 设定子参数的传递变量
	ossProvier string
	ossEndPoint string 
	accessKey string
	accessSecret string
	bucketName string
	uploadFile string
)

const (
	default_ak = "LTAI5tCZwRqpJBuJ1nDSG52c"
	default_sk = "1KiQq5bIQv047FhFg1ck77KSi2gdDa"
)
// 1. 添加一个子命令参数给rootCmd
var UploadCmd = cobra.Command{
	Use: "upload",
	Long: "upload 云中转站",
	Short: "upload 云中转站",
	Example: "upload -f filename",
	// 5. 开始先return nil , 后面加执行逻辑
 	RunE:  func(cmd *cobra.Command, args []string) error {
		var (
			uploader store.Uploader
			err error
		)
		switch ossProvier {
		case "aliyun":
			//初始化 需要传递参数 我们传递结构体 然后把我们的值给结构体中的变量
			// 我们定义了uploader变量就不需要在:= 自动推导了
			aliOpts := &aliyun.Option{
				EndPoint:  ossEndPoint,
				AccessKey: accessKey,
				AccessSecret: accessSecret,
			}
			setAliDefault(aliOpts)

			uploader, err = aliyun.NewAliOssStore(aliOpts)
			// uploader, err = aliyun.NewAliOssStore(&aliyun.Option{
			// 	//左边结构体变量 右边赋值的变量
			// 	EndPoint:  ossEndPoint,
			// 	AccessKey: accessKey,
			// 	AccessSecret: accessSecret,
			// })
		case "tx":
			uploader = tx.NewTxOssStore()
		case "aws":
			uploader = aws.NewAwsOssStore()
		default:
			return fmt.Errorf("not support oss storage provier")
		}	
		if err != nil {
			return nil 
		}
		// 使用uploader上传文件 
		return uploader.Upload(bucketName, uploadFile, uploadFile)
	
	},
}

func init() {
	// 3. 给upload加个flag 给upload加参数 赋值给f好处 多个参数就不用都写一遍
	f := UploadCmd.PersistentFlags()
	//将参数赋值给ossProvier变量
	f.StringVarP(&ossProvier, "provier", "p", "aliyun", "oss storage provier [aliyun|tx|aws]")
	f.StringVarP(&ossEndPoint, "endpoint", "e", "oss-cn-beijing.aliyuncs.com", "oss storage  provier endpoint")
	f.StringVarP(&accessKey, "access_key", "k", "", "oss storage  provier accessKey")
	f.StringVarP(&bucketName, "bucket_name", "n", "cloud-station-go7", "oss storage  provier accessKey")
	f.StringVarP(&accessSecret, "access_secret", "s", "", "oss storage  provier accessSecret")
	f.StringVarP(&uploadFile, "upload_file", "f", "", "upload file name")
	// 2. 将uploadcmd加入根命令
	RootCmd.AddCommand(&UploadCmd)
}

func setAliDefault(opts *aliyun.Option) {
	if opts.AccessKey == "" {
		opts.AccessKey = default_ak
	}
	if opts.AccessSecret == "" {
		opts.AccessSecret = default_sk
	}

}

/*
1. case是赋值变量
2. RunE是指针传递 函数中是*  调用的时候是& 指针

*/